
#import "JZMPay.h"
#import "NSData+AES.h"
#import "NSData+JZMBase64.h"
#import "JZMWebViewControler.h"
#import "JZMTokenModel.h"
#import "JZMConfigureHeader.h"
#import "WXApi.h"
#import "JZMDES.h"
#import "JZMRequest.h"
#import "JZMTimeToole.h"
#import "JZMShare.h"
#import "JZMExceptionModel.h"
#import "JZMFileManager.h"
#import "JZMCheckViewController.h"
typedef enum ParamaterTypes ParamaterType;
const NSArray *___ParamaterType;
BOOL jzmReturn;
JZMExceptionModel *jzmExceptionModel;
UIViewController *modelVc =nil;
static BOOL KDS_Log_Switch = NO;
id <JZMSDKPayDelegate> jzmMydelegate= nil;
static NSString *jzmMyToken = @"";
@interface JZMPay ()
@end

@implementation JZMPay
+ (void)getToken:(JZMTokenModel *)tokenModel returnDelegate:(id<JZMSDKPayDelegate>)delegate{
    jzmMyToken=@"";
    NSString *tokenServiceType = [tokenModel.serviceType uppercaseString];
    if (!tokenModel.p1_user_code||!tokenModel.p2_order||!tokenModel.p3_money||!tokenModel.p4_returnurl||!tokenModel.p5_notifyurl||!tokenModel.p6_ordertime||!tokenModel.p7_sign||!tokenServiceType||!tokenModel.controler||!tokenModel.payType||!tokenModel.userAppid||!tokenModel.keyString||!tokenModel.ivString||!tokenModel.zzApi){
        [delegate openAppFailer:@"参数缺失"];
        JZM_Log(@"参数缺失");
        return;
    }
    modelVc = tokenModel.controler;
    jzmExceptionModel = [JZMExceptionModel new];
    jzmExceptionModel.orderNumber = tokenModel.p2_order;
    jzmExceptionModel.usercode = tokenModel.p1_user_code;
    [jzmExceptionModel setPlatform:tokenServiceType];
    jzmExceptionModel.deviceType = [NSString stringWithFormat:@"%@ %@",[JZMTimeToole iphoneType],[[UIDevice currentDevice] systemVersion]];
    jzmExceptionModel.netType = [[JZMRequest requestManager]getNetWorkStates];
    [[JZMRequest requestManager] deviceWANIPAdress:^(NSString *returnCity) {
        jzmExceptionModel.area = returnCity;
    }];
//    if (![self getNewStr:MIWENKEY]||![self getNewStr:NONCERKEY]){
//        [self getSeverListWithTokenModel:tokenModel AndDelegate:delegate];
//    }else{
//        NSDateFormatter *formatter = [NSDateFormatter new];
//        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//        NSDate *nowDate = [JFTTimeToole getNowDateFromatAnDate:[NSDate date]];
//        NSTimeInterval interval = [nowDate timeIntervalSince1970];
//        NSString *noncer = [self getNewStr:NONCERKEY];
//        NSString *keyNonce = [[JFTDES md532BitUpper:[JZMDESKEY stringByAppendingString:noncer]] substringToIndex:8];
//        NSString *miWen = [self getNewStr:MIWENKEY];
//        NSString *mingWen = [JFTDES encryptWithContent:miWen type:1 key:keyNonce];
//        NSError *mingError;
//        NSDictionary *mingWenDic = [NSJSONSerialization JSONObjectWithData:[mingWen dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&mingError];
//        NSString *nextSync = [mingWenDic objectForKey:@"nextSync"];
//        NSDate *nextDate = [formatter dateFromString:nextSync];
//        NSDate *biaoZhun = [JFTTimeToole getNowDateFromatAnDate:nextDate];
//        NSTimeInterval nextInterval = [biaoZhun timeIntervalSince1970];
//        if (interval>nextInterval) {
//          [self getSeverListWithTokenModel:tokenModel AndDelegate:delegate];
//        }else{
        [self getNewUrl:tokenModel.zzApi WithKey:BASEJFTURLKEY];
          [self getTokenAndPayParamter:tokenModel baseUrl:[self getNewStr:BASEJFTURLKEY] returnDelegate:delegate];
//        }
//    }
}

+ (void)getPayTypeListWithAppId:(NSString *)appId userCode:(NSString *)usercode key:(NSString *)key iv:(NSString *)iv serviceType:(NSString *)serviceType zzApi:(NSString *)zzApi delegate:(id<JZMSDKPayDelegate>)delegate{
    
        if (!appId||!usercode||!key||!iv||!serviceType){
            JZM_Log(@"参数缺失");
            return;
        }
    jzmExceptionModel = [JZMExceptionModel new];
    jzmExceptionModel.usercode = usercode;
    [jzmExceptionModel setPlatform:serviceType];
    jzmExceptionModel.deviceType = [NSString stringWithFormat:@"%@ %@",[JZMTimeToole iphoneType],[[UIDevice currentDevice] systemVersion]];
    jzmExceptionModel.netType = [[JZMRequest requestManager] getNetWorkStates];
    [[JZMRequest requestManager] deviceWANIPAdress:^(NSString *returnCity) {
        jzmExceptionModel.area = returnCity;
    }];
//    if (![self getNewStr:MIWENKEY]||![self getNewStr:NONCERKEY]){
//        [self getSeverListWithappId:appId userCode:usercode key:key iv:iv serviceType:serviceType AndDelegate:delegate];
//    }else{
//        NSDateFormatter *formatter = [NSDateFormatter new];
//        [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//        NSDate *nowDate = [JFTTimeToole getNowDateFromatAnDate:[NSDate date]];
//        NSTimeInterval interval = [nowDate timeIntervalSince1970];
//        NSString *noncer = [self getNewStr:NONCERKEY];
//        NSString *keyNonce = [[JFTDES md532BitUpper:[JZMDESKEY stringByAppendingString:noncer]] substringToIndex:8];
//        NSString *miWen = [self getNewStr:MIWENKEY];
//        NSString *mingWen = [JFTDES encryptWithContent:miWen type:1 key:keyNonce];
//        NSError *mingError;
//        NSDictionary *mingWenDic = [NSJSONSerialization JSONObjectWithData:[mingWen dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&mingError];
//        NSString *nextSync = [mingWenDic objectForKey:@"nextSync"];
//        NSDate *nextDate = [formatter dateFromString:nextSync];
//        NSDate *biaoZhun = [JFTTimeToole getNowDateFromatAnDate:nextDate];
//        NSTimeInterval nextInterval = [biaoZhun timeIntervalSince1970];
//        if (interval>nextInterval) {
//            [self getSeverListWithappId:appId userCode:usercode key:key iv:iv serviceType:serviceType AndDelegate:delegate];
//        }else{
            [self getNewUrl:zzApi WithKey:BASEJFTURLKEY];
            [self getsPayTypeListWithappId:appId userCode:usercode key:key iv:iv delegate:delegate];
            
//        }
//    }
}

+(void)getSeverListWithTokenModel:(JZMTokenModel *)tokenModel AndDelegate:(id<JZMSDKPayDelegate>)delegate{
    __block NSTimeInterval jftBegin,jftEnd,mistakeTime;
    NSString *serviceType = [tokenModel.serviceType uppercaseString];
    NSDictionary *dic = @{@"SysFlag":serviceType};
    NSData *mmdata = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *enStr = [[NSString alloc]initWithData:mmdata encoding:NSUTF8StringEncoding];
    NSString *miwen = [JZMDES encryptWithContent:enStr type:0 key:[[JZMDES md532BitUpper:[JZMDESKEY stringByAppendingString:@"abcdefg"]] substringToIndex:8]];
    NSString *encodeURL = [JZMDES encodeToPercentEscapeString:[JZMDES replaceNormalCharacter:miwen]];
    NSDictionary *urlDic = @{@"JFT":@"https://123ttd1.jtpay.com",@"YHB":@"http://126g33.payhee.com",@"YZF":@"http://8756d562.payeay.com",@"WSF":@"https://21d.paywap.cn",@"QAO":@"http://ddgg5.qaopay.com"};
    NSString *myUrlString = [NSString stringWithFormat:@"%@/sdk/serverlistNew?info=%@&nonce=abcdefg",[urlDic objectForKey:serviceType],encodeURL];
    NSURL *url = [NSURL URLWithString:myUrlString];
//    JZM_Log(@"%@",url);
    //获取配置文件请求；
    jftBegin = CACurrentMediaTime();
    __weak typeof(self)weakSelf = self;
    [[JZMRequest requestManager]getDataWithUrl:url WithParameters:@{} Sucessfil:^(id returnData) {
        JZM_Log(@"%@",returnData);
        NSDictionary *returnDic = returnData;
        
        if ([[returnDic objectForKey:@"flag"] intValue] == 1){
            jftEnd = CACurrentMediaTime();
            mistakeTime = jftEnd-jftBegin;
            jzmExceptionModel.serviceTime = [NSString stringWithFormat:@"%f",mistakeTime];
            NSString *ddstr = [NSString stringWithFormat:@"%@",[JZMDES replaceSpecialCharacter:returnDic[@"msg"]]];
            [weakSelf getNewUrl:ddstr WithKey:MIWENKEY];
            [weakSelf getNewUrl:returnDic[@"nonce"] WithKey:NONCERKEY];
            NSString *keyyStr = [[JZMDES md532BitUpper:[JZMDESKEY stringByAppendingString:[returnDic objectForKey:@"nonce"]]] substringToIndex:8];
            NSString *mingWen = [JZMDES encryptWithContent:ddstr type:1 key:keyyStr];
            if (!mingWen) {
                jzmExceptionModel.serviceInfo = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:returnDic options:0 error:nil] encoding:NSUTF8StringEncoding];
                [[JZMRequest requestManager]submitInfo:jzmExceptionModel andUrl:[urlDic objectForKey:serviceType]];
                return ;
            }
            NSError *mingError;
            NSDictionary *mingwenDic = [NSJSONSerialization JSONObjectWithData:[mingWen dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&mingError];
            NSArray *services = mingwenDic[@"servers"];
            if (services.count) {
                [weakSelf getNewUrl:[services objectAtIndex:0] WithKey:BASEJFTURLKEY];
                [weakSelf getTokenAndPayParamter:tokenModel baseUrl:[self getNewStr:BASEJFTURLKEY] returnDelegate:delegate];
                JZM_Log(@"获取服务器列表成功");
            }
            
        }else{
            jzmExceptionModel.serviceInfo = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:returnDic options:0 error:nil] encoding:NSUTF8StringEncoding];
            [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:[urlDic objectForKey:serviceType]];
            [weakSelf getNewUrl:[urlDic objectForKey:serviceType] WithKey:BASEJFTURLKEY];
            JZM_Log(@"获取服务器列表失败");
            [delegate openAppFailer:returnDic[@"msg"]];
            
        }
        
    } failure:^(id failerObjc) {
        //        failly (failerObjc);
        [delegate openAppFailer:failerObjc];
    }error:^(NSError *err) {
        jzmExceptionModel.serviceInfo =[NSString stringWithFormat:@"%zi",err.code];
        [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:[urlDic objectForKey:serviceType]];
        [weakSelf getNewUrl:[urlDic objectForKey:serviceType] WithKey:BASEJFTURLKEY];
        [weakSelf getTokenAndPayParamter:tokenModel baseUrl:[self getNewStr:BASEJFTURLKEY] returnDelegate:delegate];
        JZM_Log(@"获取服务器列表失败");
    }];
}

+(void)getSeverListWithappId:(NSString *)appId userCode:(NSString *)usercode key:(NSString *)key iv:(NSString *)iv serviceType:(NSString *)ServiceType AndDelegate:(id<JZMSDKPayDelegate>)delegate{
    __block NSTimeInterval jftBegin,jftEnd,mistakeTime;
    NSString *serviceType = [ServiceType uppercaseString];
    NSDictionary *dic = @{@"SysFlag":serviceType};
    NSData *mmdata = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
    NSString *enStr = [[NSString alloc]initWithData:mmdata encoding:NSUTF8StringEncoding];
    
    NSString*miwen = [JZMDES encryptWithContent:enStr type:0 key:[[JZMDES md532BitUpper:[JZMDESKEY stringByAppendingString:@"abcdefg"]] substringToIndex:8]];
    
    NSString *encodeURL = [JZMDES encodeToPercentEscapeString:[JZMDES replaceNormalCharacter:miwen]];
    NSDictionary *urlDic = @{@"JFT":@"https://123ttd1.jtpay.com",@"YHB":@"http://126g33.payhee.com",@"YZF":@"http://8756d562.payeay.com",@"WSF":@"https://21d.paywap.cn",@"QAO":@"http://ddgg5.qaopay.com"};
    NSString *myUrlString = [NSString stringWithFormat:@"%@/sdk/serverlistNew?info=%@&nonce=abcdefg",[urlDic objectForKey:serviceType],encodeURL];
    NSURL *url = [NSURL URLWithString:myUrlString];
//    JZM_Log(@"%@",url);
    //获取配置文件请求；
    jftBegin = CACurrentMediaTime();
    __weak typeof(self)weakSelf = self;
    [[JZMRequest requestManager]getDataWithUrl:url WithParameters:@{} Sucessfil:^(id returnData) {
        JZM_Log(@"%@",returnData);
        NSDictionary *returnDic = returnData;
        
        if ([[returnDic objectForKey:@"flag"] intValue] == 1){
            jftEnd = CACurrentMediaTime();
            mistakeTime = jftEnd-jftBegin;
            jzmExceptionModel.serviceTime = [NSString stringWithFormat:@"%f",mistakeTime];
            NSString *ddstr = [NSString stringWithFormat:@"%@",[JZMDES replaceSpecialCharacter:returnDic[@"msg"]]];
            [weakSelf getNewUrl:ddstr WithKey:MIWENKEY];
            [weakSelf getNewUrl:returnDic[@"nonce"] WithKey:NONCERKEY];
            NSString *keyyStr = [[JZMDES md532BitUpper:[JZMDESKEY stringByAppendingString:[returnDic objectForKey:@"nonce"]]] substringToIndex:8];
            NSString*mingWen = [JZMDES encryptWithContent:ddstr type:1 key:keyyStr];
            if (!mingWen) {
                jzmExceptionModel.serviceInfo = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:returnDic options:0 error:nil] encoding:NSUTF8StringEncoding];
                [[JZMRequest requestManager]submitInfo:jzmExceptionModel andUrl:[urlDic objectForKey:serviceType]];
                return ;
            }
            NSError *mingError;
            NSDictionary *mingwenDic = [NSJSONSerialization JSONObjectWithData:[mingWen dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&mingError];
            NSArray *services = mingwenDic[@"servers"];
            if (services.count) {
                [weakSelf getNewUrl:[services objectAtIndex:0] WithKey:BASEJFTURLKEY];
                [weakSelf getsPayTypeListWithappId:appId userCode:usercode key:key iv:iv delegate:delegate];
                JZM_Log(@"获取服务器列表成功");
            }
            
        }else{
            jzmExceptionModel.serviceInfo = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:returnDic options:0 error:nil] encoding:NSUTF8StringEncoding];
            [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:[urlDic objectForKey:serviceType]];
            [weakSelf getNewUrl:[urlDic objectForKey:serviceType] WithKey:BASEJFTURLKEY];
            JZM_Log(@"获取服务器列表失败");
            [delegate openAppFailer:returnDic[@"msg"]];

        }
        
    } failure:^(id failerObjc) {
        [delegate openAppFailer:failerObjc];
    }error:^(NSError *err) {
        jzmExceptionModel.serviceInfo = [NSString stringWithFormat:@"%zi",err.code];
        [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:[urlDic objectForKey:serviceType]];
        [weakSelf getNewUrl:[urlDic objectForKey:serviceType] WithKey:BASEJFTURLKEY];
         [weakSelf getsPayTypeListWithappId:appId userCode:usercode key:key iv:iv delegate:delegate];
        JZM_Log(@"获取服务器列表失败");
    }];
}

+ (void) getsPayTypeListWithappId:(NSString *)appId userCode:(NSString *)usercode key:(NSString *)key iv:(NSString *)iv  delegate:(id<JZMSDKPayDelegate>)delegate{
    
    NSString *payUrl = [self getNewStr:BASEJFTURLKEY];
    if (![self getNewStr:BASEJFTURLKEY]) {
        [delegate getPayTypeListFailure:errorParma];
        return;
    }
    
    NSDictionary *dic = @{@"usercode":usercode,@"packagename":PACKAGENAME,@"devicetype":@"2"};
    NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc]initWithDictionary:dic];
    NSError *jsonError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:&jsonError];
    NSData *tokenData = [jsonData AES256EncryptWithKey:key iv:iv];
    NSString *jsonBase64 = [JZMDES replaceNormalCharacter:[tokenData base64EncodedString]];
    NSString *encodeBase = [JZMDES encodeToPercentEscapeString:jsonBase64];
    NSString *serchPath = [NSString stringWithFormat:@"%@/SDK/GetPayTypeList?appid=%@&info=%@",payUrl,appId,encodeBase];
    JZM_Log(@"获取列表---%@",[NSString stringWithFormat:@"appid=%@&info=%@",appId,encodeBase]);
    NSURL *url = [NSURL URLWithString:serchPath];
    
    __block NSTimeInterval jftBegin,jftEnd,mistakeTime;
    jftBegin = CACurrentMediaTime();
    [[JZMRequest requestManager]getDataWithUrl:url WithParameters:@{} Sucessfil:^(id returnData) {
        if ([returnData isKindOfClass:[NSDictionary class]]) {
            NSDictionary *returnDic = returnData;
            NSString *flag = [returnDic objectForKey:@"flag"];
            NSString *message = [returnDic objectForKey:@"msg"];
            if ([flag isEqualToString:@"1"]) {
                jftEnd = CACurrentMediaTime();
                mistakeTime = jftEnd-jftBegin;
                jzmExceptionModel.paylistTime = [NSString stringWithFormat:@"%f",mistakeTime];
                NSData *de_data = [[NSData dataFromBase64String:[JZMDES replaceSpecialCharacter:message]] AES256DecryptWithKey:key iv:iv];
                if (!de_data) {
                    jzmExceptionModel.tokenInfo = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:dic options:0 error:nil] encoding:NSUTF8StringEncoding];
                    [[JZMRequest requestManager]submitInfo:jzmExceptionModel andUrl:url.absoluteString];
                    return ;
                }
                NSError *enError;
                NSArray *listArray = [NSJSONSerialization
                                      JSONObjectWithData:de_data
                                      options:NSJSONReadingAllowFragments
                                      error:&enError];
                [delegate getPayTypeListSuccess:listArray];
                JZM_Log(@"获取列表成功");
            }else{
                jzmExceptionModel.paylistInfo = message;
                [delegate getPayTypeListFailure:message];
            }
        }
    } failure:^(id failerObjc) {
        [delegate getPayTypeListFailure:failerObjc];
    } error:^(NSError *err) {
        jzmExceptionModel.paylistInfo = [NSString stringWithFormat:@"%zi",err.code];
        [[JZMRequest requestManager]submitInfo:jzmExceptionModel andUrl:payUrl];
        [delegate getPayTypeListFailure:[NSString stringWithFormat:@"%zi",err.code]];
    }];
    
}

+  (void)getTokenAndPayParamter:(JZMTokenModel *)tokenModel baseUrl:(NSString*)baseUrl returnDelegate:(id<JZMSDKPayDelegate>)delegate{
    NSMutableDictionary *endic = [JZMFileManager readAllData];
    if (endic) {
        NSArray *dataArray = [endic objectForKey:@"info"];
        if (dataArray.count >= 5) {
            [[JZMRequest requestManager] submitInfo:nil andUrl:baseUrl] ;
        }
    }
    jzmReturn = tokenModel.isReturn;
    jzmMydelegate = delegate;
    NSString *iphoneInfo = [NSString stringWithFormat:@"%@ %@",[JZMTimeToole iphoneType],[[UIDevice currentDevice] systemVersion]];
    NSDictionary *ddic = @{@"p1_usercode":tokenModel.p1_user_code,@"p2_order":tokenModel.p2_order,@"p3_money":tokenModel.p3_money,@"p4_returnurl":tokenModel.p4_returnurl,@"p5_notifyurl":tokenModel.p5_notifyurl,@"p6_ordertime":tokenModel.p6_ordertime,@"p7_sign":tokenModel.p7_sign,@"ext_device":iphoneInfo,@"ext_sdkversion":EXT_SDKVERSON,@"p9_paymethod":@"SDK",@"ext_paytype":tokenModel.payType,@"packagename":PACKAGENAME,@"p25_terminal":@"2",@"p26_iswappay":@"5"};
    NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc]initWithDictionary:ddic];
    if (tokenModel.parameterDic) {
        NSArray *keyArray = [tokenModel.parameterDic allKeys];
        NSArray *valueArray = [tokenModel.parameterDic allValues];
        if (valueArray.count) {
            for (int i = 0; i < valueArray.count; i++) {
                if (![valueArray[i] isEqualToString:@""]) {
                    [jsonDic setObject:[NSString stringWithFormat:@"%@",valueArray[i]] forKey:[NSString stringWithFormat:@"%@",keyArray[i]]];
                }
            }
        }
    }
    NSError *jsonError;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:&jsonError];
    NSData *tokenData = [jsonData AES256EncryptWithKey:tokenModel.keyString iv:tokenModel.ivString];
    NSString *jsonBase64 =[tokenData base64EncodedString];
    jsonBase64 = [JZMDES replaceNormalCharacter:jsonBase64];
    NSString *encodeBase = [JZMDES encodeToPercentEscapeString:jsonBase64];
    NSString *serchPath = [NSString stringWithFormat:@"%@/sdk/StepPayNew?appid=%@&info=%@",baseUrl,tokenModel.userAppid,encodeBase];
    JZM_Log(@"获取支付参数---%@",[NSString stringWithFormat:@"appid=%@&info=%@",tokenModel.userAppid,encodeBase]);
    NSURL *jfturl = [NSURL URLWithString:serchPath];
    __block NSTimeInterval jftBegin,jftEnd,mistakeTime;
    jftBegin = CACurrentMediaTime();
    [[JZMRequest requestManager]getDataWithUrl:jfturl WithParameters:@{} Sucessfil:^(id returnData) {
        if ([returnData isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dic = returnData;
            jftEnd = CACurrentMediaTime();
            mistakeTime = jftEnd-jftBegin;
            jzmExceptionModel.tokenTime = [NSString stringWithFormat:@"%f",mistakeTime];
            if ([dic[@"flag"] isEqualToString:@"1"]){
                NSData *de_data = [[NSData dataFromBase64String:[NSString stringWithFormat:@"%@",[JZMDES replaceSpecialCharacter:dic[@"msg"]]]] AES256DecryptWithKey:tokenModel.keyString iv:tokenModel.ivString];
                NSError *enError;
                if (!de_data) {
                    JZM_Log(@"=======解密失败========");
                    jzmExceptionModel.tokenInfo = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:dic options:0 error:nil] encoding:NSUTF8StringEncoding];
                    [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:baseUrl];
                }
                if ([[NSJSONSerialization
                      JSONObjectWithData:de_data
                      options:NSJSONReadingAllowFragments
                      error:&enError] isKindOfClass:[NSDictionary class]]) {
                    NSDictionary *tokenDic = [NSJSONSerialization
                                            JSONObjectWithData:de_data
                                            options:NSJSONReadingAllowFragments
                                            error:&enError];
//                JZM_Log(@"%@",tokenDic);
                    jzmExceptionModel.remark = tokenModel.payType;
                if ([tokenModel.payType intValue] == 3||[tokenModel.payType intValue] == 11||[tokenModel.payType intValue] == 12) {
                    if (![self isInstallApp:[tokenModel.payType integerValue]]) {
                        if ([tokenModel.payType intValue] == 3) {
                            [delegate openAppFailer:@"未安装微信"];
                        }
                        if ([tokenModel.payType intValue] == 11) {
                            [delegate openAppFailer:@"未安装QQ"];
                        }
                    }else{
                    dispatch_async(dispatch_get_main_queue(), ^{
                     
                    [self payByWeichat:tokenDic[@"paramlist"] returnDelegate:delegate andcontroler:tokenModel.controler andisReturn:tokenModel.isReturn andBaseUrl:baseUrl];
                    });
                  jzmMyToken = [tokenDic objectForKey:@"token"];
                    }
                }
                if ([tokenModel.payType intValue] == 4) {
                    if (![self isInstallApp:[tokenModel.payType integerValue]]) {
                        [delegate openAppFailer:@"未安装支付宝"];
                    }else{
//                        JZM_Log(@"%@",tokenDic);
                    dispatch_async(dispatch_get_main_queue(), ^{
                     
                         [self payByalipay:tokenDic[@"paramlist"] returnDelegate:delegate andcontroler:tokenModel.controler andisReturn:tokenModel.isReturn andBaseUrl:baseUrl];
                    });
                      jzmMyToken = [tokenDic objectForKey:@"token"];
                    }
                }
            }else{
                jzmExceptionModel.tokenInfo = [NSJSONSerialization
                                              JSONObjectWithData:de_data
                                              options:NSJSONReadingAllowFragments
                                              error:&enError];
                [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:baseUrl];
                [delegate openAppFailer:[NSJSONSerialization
                                         JSONObjectWithData:de_data
                                         options:NSJSONReadingAllowFragments
                                         error:&enError]];
            }
            }else{
                jzmExceptionModel.tokenInfo = [[NSString alloc]initWithData:[NSJSONSerialization dataWithJSONObject:dic options:0 error:nil] encoding:NSUTF8StringEncoding];
                [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:baseUrl];
                [delegate openAppFailer:dic[@"msg"]];
            }
        }
    } failure:^(id failerObjc) {
        [delegate openAppFailer:failerObjc];
        jzmMyToken = @"";
    } error:^(NSError *err) {
        jftEnd = CACurrentMediaTime();
        mistakeTime = jftEnd-jftBegin;
        jzmExceptionModel.tokenTime = [NSString stringWithFormat:@"%f",mistakeTime];
        jzmExceptionModel.tokenInfo = [NSString stringWithFormat:@"获取token的错误码为%zi",err.code];
        [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:baseUrl];
        if ([self getNewStr:NONCERKEY]&&[self getNewStr:MIWENKEY]) {
            NSString *keyyStr = [[JZMDES md532BitUpper:[JZMDESKEY stringByAppendingString:[self getNewStr:NONCERKEY]]] substringToIndex:8];
            NSString *mingWen = [JZMDES encryptWithContent:[self getNewStr:MIWENKEY] type:1 key:keyyStr];
            NSError *mingError;
            NSDictionary *mingWenDic = [NSJSONSerialization JSONObjectWithData:[mingWen dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&mingError];
            NSArray *services = mingWenDic[@"servers"];
            BOOL isbool = [services containsObject: [self getNewStr:BASEJFTURLKEY]];
            if (isbool) {
                NSInteger i = [services indexOfObject:[self getNewStr:BASEJFTURLKEY]];
                if (i == services.count-1) {
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:MIWENKEY];
                    [[NSUserDefaults standardUserDefaults] removeObjectForKey:NONCERKEY];
                    [delegate openAppFailer:@"参数获取失败请重新支付"];
                    jzmMyToken=@"";
                }else{
                    NSString *nextURL = [services objectAtIndex:i+1];
                    [self getNewUrl:nextURL WithKey:BASEJFTURLKEY];
                    [delegate openAppFailer:@"参数获取失败请重新支付"];
                    jzmMyToken = @"";
                }
            }
        }else{
            [delegate openAppFailer:@"参数获取失败请重新支付"];
            jzmMyToken = @"";
        }
        return ;
    }];
}

+ (void)payByalipay:(NSArray *)paramlist returnDelegate:(id<JZMSDKPayDelegate>)delegate andcontroler:(UIViewController *)controler andisReturn:(BOOL)isReturns andBaseUrl:(NSString*)baseUrl{
    NSString * isopen = @"";
    NSString * img = @"";
    NSString * invoketype = @"";
//    JZM_Log(@"%@",paramlist);
    __block NSTimeInterval jftBegin,jftEnd,mistakeTime;
    jftBegin = CACurrentMediaTime();
    for (int i = 0; i < paramlist.count;i++) {
        NSDictionary<NSString *,NSString *> * paramater = [paramlist objectAtIndex:i];
        NSString * paramCode = [paramater objectForKey:@"paramcode"];
        switch (cdPodRecordTypeEnum(paramCode)) {
            case isOpen:
                isopen = [paramater objectForKey:@"paramvalue"];
                break;
            case isImgUrl:
                if ([paramater objectForKey:@"paramvalue"] == nil||[[paramater objectForKey:@"paramvalue"] isKindOfClass:[NSNull class]]||[[paramater objectForKey:@"paramvalue"] isEqualToString:@""]) {
                    jzmExceptionModel.remark = @"img未获取到参数";
                    [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:baseUrl];
                    [delegate openAppFailer:@"未获取到参数"];
                    jzmMyToken = @"";
                    return;
                }else{
                    img = [paramater objectForKey:@"paramvalue"];
                }
                break;
            case isSDKFlag:
                [delegate jzmPayResult:@"威富通还未接入"];
                JZM_Log(@"威富通还未接入");
                return;
                break;
            case isInvoketype:
                if ([[paramater objectForKey:@"paramvalue"] isKindOfClass:[NSNull class]]) {
                    JZM_Log(@"invoketype为空");
                    return;
                }else{
                    invoketype = [paramater objectForKey:@"paramvalue"];
                }
                break;
            default:
                break;
        }
    }
    if (![img isEqualToString:@""]) {
        if ([img isKindOfClass:[NSNull class]]) {
            [delegate openAppFailer:errorParma];
            jzmMyToken = @"";
            return;
        }
        if ([isopen isEqualToString:@"1"]) {
            JZM_Log(@"alipay gouka");
            JZMWebViewControler *webvc = [[JZMWebViewControler alloc]init];
            webvc.diVc = controler;
            webvc.webUrl = img;
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:webvc];
            dispatch_async(dispatch_get_main_queue(), ^{
                [controler presentViewController:nav animated:YES completion:nil];
            });
        }else if ([invoketype isEqualToString:@"1"]) {
            JZM_Log(@"alipay yemian chu li");
            if (JZMIOS_VERSION_10) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"alipays://platformapi/startapp?appId=20000067&&url=%@",img]] options:@{} completionHandler:^(BOOL success) {
                    if (success) {
                        [delegate openAppSuccessed];
                    }
                }];
            }else{
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:[NSString stringWithFormat:@"alipays://platformapi/startapp?appId=20000067&&url=%@",img]]];
                [delegate openAppSuccessed];
            }
        }
        else{
            if ([[UIApplication sharedApplication]canOpenURL:[NSURL URLWithString:img]]==NO) {
                [delegate openAppFailer:img];
                jzmMyToken = @"";
                return;
            }
            JZM_Log(@"alipay SDK");
            [[JZMShare shareInstance]requestWithWebView:nil andUrl:img];
            [JZMShare shareInstance].openComplete = ^(BOOL status) {
                if (status) {
                    jftEnd = CACurrentMediaTime();
                    mistakeTime = jftEnd-jftBegin;
                    jzmExceptionModel.payTime = [NSString stringWithFormat:@"%f",mistakeTime];
                    [JZMFileManager addModel:jzmExceptionModel];
                    [delegate openAppSuccessed];
                }else{
                    jzmExceptionModel.remark = img;
                    [[JZMRequest requestManager]submitInfo:jzmExceptionModel andUrl:baseUrl];
                    [delegate openAppFailer:@"打开失败"];
                }
            };
        }
    }
}

+ (void)payByWeichat:(NSArray *)paramlist returnDelegate:(id<JZMSDKPayDelegate>)delegate andcontroler:(UIViewController*)controler andisReturn:(BOOL)isReturns andBaseUrl:(NSString *)baseUrl{
    NSString *isopen = @"";
    NSString *img = @"";
    NSString *sdkflag = @"";
    NSString *payToken = @"";
    jzmReturn =NO;
    __block NSTimeInterval jftBegin,jftEnd,mistakeTime;
    jftBegin = CACurrentMediaTime();
    for (int i = 0; i < paramlist.count; i++) {
        NSDictionary<NSString *,NSString *> * paramater = [paramlist objectAtIndex:i];
        NSString *paramCode = [paramater objectForKey:@"paramcode"];
        switch (cdPodRecordTypeEnum(paramCode)) {
            case isOpen:
                isopen = [paramater objectForKey:@"paramvalue"];
                break;
            case isImgUrl:
                if ([paramater objectForKey:@"paramvalue"] == nil||[[paramater objectForKey:@"paramvalue"] isKindOfClass:[NSNull class]]||[[paramater objectForKey:@"paramvalue"] isEqualToString:@""]) {
                    [delegate openAppFailer:@"未获取到参数"];
                    jzmMyToken = @"";
                    jzmExceptionModel.remark = @"img未获取到参数";
                    [[JZMRequest requestManager] submitInfo:jzmExceptionModel andUrl:baseUrl];
                    return;
                }else{
                    img = [paramater objectForKey:@"paramvalue"];
                }
                break;
            case isSDKFlag:
                if ([[paramater objectForKey:@"paramvalue"] isKindOfClass:[NSNull class]]) {
                    JZM_Log(@"token_id为空");
                    return;
                }else
                    sdkflag = [paramater objectForKey:@"paramvalue"];
                JZM_Log(@"sdkflag=%@",sdkflag);
                break;
            case isPayToken:
                if ([[paramater objectForKey:@"paramvalue"] isKindOfClass:[NSNull class]]) {
                    JZM_Log(@"payToken为空");
                    return;
                }else
                    payToken = [paramater objectForKey:@"paramvalue"];
                JZM_Log(@"payToken=%@",payToken);
                break;
            case isWxappid:
                if ([[paramater objectForKey:@"paramvalue"] isKindOfClass:[NSNull class]]) {
                    JZM_Log(@"Wxappid为空");
                    return;
                }
                break;
            default:
                break;
        }
    }
    if (![img isEqualToString:@""]) {
        if ([isopen isEqualToString:@"1"]) {
            JZMWebViewControler *webvc = [[JZMWebViewControler alloc]init];
            webvc.diVc = controler;
            webvc.webUrl = img;
            UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:webvc];
            dispatch_async(dispatch_get_main_queue(), ^{
                [controler presentViewController:nav animated:YES completion:^{
                    if ([img hasPrefix:@"https://h5pay.jd"]) {
                        jftEnd = CACurrentMediaTime();
                        mistakeTime = jftEnd - jftBegin;
                        jzmExceptionModel.payTime =[NSString stringWithFormat:@"%f",mistakeTime];
                        [JZMFileManager addModel:jzmExceptionModel];
                    }
                    [delegate openAppSuccessed];
                }];
            });
            webvc.didClickCancel = ^(){
                jzmReturn = isReturns;
                [self getResultAndReturnDelegate:delegate];
            };
            webvc.begainOpen = ^(BOOL status) {
                jftBegin = CACurrentMediaTime();
            };
            webvc.openComplete = ^(BOOL status, NSString *urlStr) {
                if (status) {
                    jzmReturn = isReturns;
                    jftEnd = CACurrentMediaTime();
                    mistakeTime = jftEnd -jftBegin;
                    jzmExceptionModel.payTime = [NSString stringWithFormat:@"%f",mistakeTime];
                    [JZMFileManager addModel:jzmExceptionModel];
                }
            };
        }else {
            if ([img hasPrefix:@"weixin://"]) {
                if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:img]]) {
                    jzmReturn = isReturns;
                    jftEnd = CACurrentMediaTime();
                    mistakeTime = jftEnd - jftBegin;
                    jzmExceptionModel.payTime = [NSString stringWithFormat:@"%f",mistakeTime];
                    [self openApplicationWithUrlString:img];
                    [JZMFileManager addModel:jzmExceptionModel];
                    [delegate openAppSuccessed];
                    return;
                }else{
                    [delegate openAppFailer:errorParma];
                    jzmMyToken = @"";
                    return;
                }
            }
            if ([img hasPrefix:@"http"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                         [[JZMShare shareInstance]requestWithWebView:nil andUrl:img];
                });
                [JZMShare shareInstance].openComplete = ^(BOOL status) {
                    if (status) {
                        jzmReturn = isReturns;
                        jftEnd = CACurrentMediaTime();
                        mistakeTime = jftEnd-jftBegin;
                        jzmExceptionModel.payTime = [NSString stringWithFormat:@"%f",mistakeTime];
                        [JZMFileManager addModel:jzmExceptionModel];
                        [delegate openAppSuccessed];
                    }else{
                        [delegate openAppFailer:@"打开失败"];
                        jzmExceptionModel.remark = img;
                        [[JZMRequest requestManager]submitInfo:jzmExceptionModel andUrl:baseUrl];
                    }
                };
            }
        }
    }
}

+ (void)getResultAndReturnDelegate:(id<JZMSDKPayDelegate>)delegate{
    if (!jzmReturn) {
        return;
    }
    if (!jzmMyToken||[jzmMyToken isEqualToString:@""]) {
        return;
    }
    NSString *urlString = [NSString stringWithFormat:@"%@/SDK/tokenQuery?token=%@",[self getNewStr:BASEJFTURLKEY],jzmMyToken];
    __block NSTimeInterval jftBegin,jftEnd,mistakeTime;
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLSession *sesson = [NSURLSession sharedSession];
    jftBegin =CACurrentMediaTime();
    NSURLSessionDataTask *task = [sesson dataTaskWithRequest:[NSURLRequest requestWithURL:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        jftEnd =CACurrentMediaTime();
        mistakeTime = jftEnd - jftBegin;
        jzmExceptionModel.callbackTime =[NSString stringWithFormat:@"%f",mistakeTime];
        [JZMFileManager changeDataWith:jzmExceptionModel];
        if (!data) {
            [jzmMydelegate jzmPayResult:@"-1"];
            jzmMyToken = nil;
            jzmReturn = NO;
            return ;
        }
        if (error) {
            [jzmMydelegate jzmPayResult:@"-1"];
            jzmMyToken = nil;
            jzmReturn = NO;
            return;
        }
        NSError *jftError;
        NSDictionary *dic =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jftError];
        if ([[dic objectForKey:@"flag"] isEqualToString:@"success"]) {
            if ([[dic objectForKey:@"msg"] isEqualToString:@"0"]) {
                JZMCheckViewController *jftCHvc = [JZMCheckViewController new];
                jftCHvc.jzmCheckToken = jzmMyToken;
                jzmMyToken = nil;
                jzmReturn = NO;
                dispatch_async(dispatch_get_main_queue(), ^{
                    [modelVc presentViewController:jftCHvc animated:NO completion:nil];
                });
                jftCHvc.openComplete = ^(NSString *result) {
                    if ([result integerValue] == 0) {
                        [self payResultType:notPaidType];
                    }
                    if ([result integerValue] == 1) {
                        [self payResultType:hadPaidType];
                    }
                    if ([result integerValue] == -1) {
                        [self payResultType:errorPaidType];
                    }
                };
            }
            if ([[dic objectForKey:@"msg"] isEqualToString:@"1"]) {
                jzmMyToken = nil;
                jzmReturn = NO;
                [self payResultType:hadPaidType];
            }
        }else{
            jzmExceptionModel.remark = url.absoluteString;
            [[JZMRequest requestManager]submitInfo:jzmExceptionModel andUrl:[self getNewStr:BASEJFTURLKEY]];
            JZMCheckViewController *jftCHvc = [JZMCheckViewController new];
            jftCHvc.jzmCheckToken = jzmMyToken;
            jzmMyToken = nil;
            jzmReturn = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                [modelVc presentViewController:jftCHvc animated:NO completion:nil];
            });
            jftCHvc.openComplete = ^(NSString *result) {
                if ([result integerValue] == 0) {
                    [self payResultType:notPaidType];
                }
                if ([result integerValue] == 1) {
                    [self payResultType:hadPaidType];
                }
                if ([result integerValue] == -1) {
                    [self payResultType:errorPaidType];
                }
            };
        }
    }];
    [task resume];
}

+ (void)getNewUrl:(NSString *)newUrl WithKey:(NSString *)key{
    NSUserDefaults *jftDefaults = [NSUserDefaults standardUserDefaults];
    [jftDefaults removeObjectForKey:key];
    [jftDefaults setObject:newUrl forKey:key];
    [jftDefaults synchronize];
}

+ (NSString *)getNewStr:(NSString *)key{
    
    return [[NSUserDefaults standardUserDefaults]objectForKey:key];
}

+ (void)sendWeChatOrignSDKPayJson:(NSString *)json{
    NSData *nyData = [json dataUsingEncoding:NSUTF8StringEncoding];
    NSError *nyerror = nil;
    NSDictionary *nyDic = [NSJSONSerialization JSONObjectWithData:nyData options:NSJSONReadingMutableContainers error:&nyerror];
    BOOL isJson = [WXApi registerApp:@"wx1d6775c7e499caa9"];
    if (isJson) {
        PayReq *payReq = [PayReq new];
        payReq.partnerId = nyDic[@"partnerid"];
        payReq.prepayId = nyDic[@"prepayid"];
        payReq.nonceStr = nyDic[@"noncestr"];
        payReq.package = nyDic[@"package"];
        payReq.sign = [NSString stringWithFormat:@"%@",nyDic[@"sign"]];
        payReq.timeStamp = [nyDic[@"timestamp"] intValue];
        [WXApi sendReq:payReq];
    }
}

+ (BOOL)isInstallApp:(PaymentType)type{
    if (type == jdPaymentType) {
        return YES;
    }else{
    NSDictionary *typeDic = @{@"3":@"weixin://",@"4":@"alipay:",@"11":@"mqq://"};
    NSString *keyStr = [NSString stringWithFormat:@"%lu",(unsigned long)type];
    return [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[typeDic objectForKey:keyStr]]];
    }
}

+ (void)applicationWillEnterForeground{
    [self getResultAndReturnDelegate:jzmMydelegate];
}

+ (void)payResultType:(jftResultType)result{
    switch (result) {
        case hadPaidType:
            [jzmMydelegate jzmPayResult:@"1"];
            break;
        case notPaidType:
            [jzmMydelegate jzmPayResult:@"0"];
            break;
        case errorPaidType:
            [jzmMydelegate jzmPayResult:@"-1"];
            break;
        default:
            break;
    }
}

+ (void)openApplicationWithUrlString:(NSString *)urlString{
//    JZM_Log(@"%@",urlString);
    if (JZMIOS_VERSION_10) {
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:^(BOOL success) {
            if (success) {
                JZM_Log(@"打开成功");
            }else
                JZM_Log(@"打开失败");
        }];
    }else{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];
    }
}

void customLog(const char *func, int lineNumber, NSString *format, ...)
{
    if ([JZMPay logEnable]) {// 开启了Log
        va_list args;
        va_start(args, format);
        NSString *string = [[NSString alloc] initWithFormat:format arguments:args];
        va_end(args);
        NSString *strFormat = [NSString stringWithFormat:@"%s, Line:%i, SDK_Log:%@",func,lineNumber,string];
        NSLog(@"%@", strFormat);
    }
}

+ (BOOL)logEnable {
    return KDS_Log_Switch;
}

+ (void)setLogEnable:(BOOL)flag {
    KDS_Log_Switch = flag;
}

@end
